function C_prepareArduino(ID)

global CG; if nargin<1 ID = 1; end

% REMOVE THE DATA OF THE CURRENT ARDUINO ACQUISITION
FN = fieldnames(CG.Data.Arduino);
for iF=1:length(FN) CG.Data.Arduino(ID).(FN{iF}) = []; end
CG.Sessions.Arduino(ID).CurrentSize = 0;
CG.Sessions.Arduino(ID).ReadTimes = [];
CG.Sessions.Arduino(ID).LastTime = 0;
CG.Sessions.Arduino(ID).LastSavedPacket = 0;
CG.Sessions.Arduino(ID).LastSavedEvent = 0;
CG.Events.Arduino(ID).Events = struct('Name',{},'Data',{},'Time',{});

if strcmp(get(CG.Sessions.Arduino(ID).S,'Status'),'open')
  C_stopArduino(ID); C_closeArduino(ID)
end

% CHECK WHETHER CURRENT SERIAL DEVICE ALREADY USED
[Pars,PS] = C_getParametersModule('ModuleType','Arduino','IDType',ID);
if ~strcmp(PS.SerialPort,CG.Sessions.Arduino(ID).SerialPort)
  IDs = 1:length(CG.Sessions.Arduino);
  SerialPortsInUse = {};
  for cID=IDs
    if cID~=ID
      if ~isempty(CG.Sessions.Arduino(cID).S)
        SerialPortsInUse{cID} = CG.Sessions.Arduino(cID).SerialPort;
      end
    end
  end
  MatchIDs = find(strcmp(SerialPortsInUse,PS.SerialPort));
  if ~isempty(MatchIDs)
    for iA=MatchIDs
      try fclose(CG.Sessions.Arduino(iA).S); end
      C_deleteArduino(iA);
      set(CG.GUI.Main.Modules.Arduino(iA).StartButton,'Enable','off');
    end
  end
  C_setArduinoPort(ID,PS.SerialPort);
else
  if isempty(CG.Sessions.Arduino(ID).S)
    C_setArduinoPort(ID,PS.SerialPort);
  end
end

% PREPARE PARAMETERS FOR SERIAL PORT
CG.Sessions.Arduino(ID).ControlInterval = PS.ControlInterval;
BitsPerCallback = CG.Parameters.Arduino.BaudRate*PS.ControlInterval;
BitsPerPacket = CG.Parameters.Arduino.BytesPerPacket*8;
NPackets = floor(BitsPerCallback/BitsPerPacket);
CG.Sessions.Arduino(ID).BytesAvailableFcnCount = NPackets*BitsPerPacket/8;
set(CG.Sessions.Arduino(ID).S,...
  'BytesAvailableFcnCount',CG.Sessions.Arduino(ID).BytesAvailableFcnCount);

% PREPARE VARIABLES
CG.Sessions.Arduino(ID).PacketsAcquired = 0;
CG.Sessions.Arduino(ID).Iteration = 0;

C_Logger('C_prepareArduino','Arduino ready to start ...\n');
fopen(CG.Sessions.Arduino(ID).S); pause(0.95);
BA = get(CG.Sessions.Arduino(ID).S,'BytesAvailable');
if BA fread(CG.Sessions.Arduino(ID).S,BA); end
C_sendMessageArduino(ID,'stop');
try set(CG.GUI.Main.Modules.Arduino(ID).StartButton,'Value',0,'BackgroundColor',[0,1,0]); end
